import { Text, StyleSheet, View, SafeAreaView, FlatList, TouchableWithoutFeedback, ActivityIndicator } from 'react-native'
import React, { useEffect, useRef, useState } from 'react'
import { connect } from 'react-redux'
import { pTx } from "../../utils/dimensions"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import Avatar from "../../components/avatar"
import IconFont from '@pingtou/rn-vant-icons'
import httpApi from "../../api"

const CreateGroupChat = (props) => {
    const realm = useRealm();
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const friendList = useQuery(schemaName.FriendList, friend => {
        return friend.filtered(`UserId == ${userInfo.Id}`)
    })


    const [list, setList] = useState([])
    const [loading, setLoading] = useState()

    useEffect(() => {
        props.navigation.setOptions({
            headerRight: ({ options }) => (
                <TouchableWithoutFeedback disabled={loading} onPress={() => sendGroupCreate()}>
                    <View style={[styles.flexDirectionRow, styles.headerTitleObx, list.length > 0 && styles.headerTitleHave]}>
                        {loading && <ActivityIndicator color="#ffffff" />}
                        <Text style={[styles.headerTitle, list.length > 0 && styles.headerTitleHave]} ellipsizeMode={'tail'} numberOfLines={1}>
                            完成({list.length})
                        </Text>
                    </View>
                </TouchableWithoutFeedback>
            )
        });
    }, [list.length, loading])


    const sendGroupCreate = async () => {
        try {
            if (list.length == 0) return
            setLoading(true)
            const res = await httpApi.sendGroupCreate({ ids: list.map(item => item.F).join(","), groupName: "群聊", groupLogo: httpApi.defaultAvatar })
            if (res.code == 20) {
                const getGroupList = await httpApi.getGroupList()
                realm.write(() => {
                    getGroupList.data.GroupList && getGroupList.data.GroupList.map(item => realm.create(schemaName.GroupList, { ...item, UserId: userInfo.Id, State: 1 }, true))
                })
                props.navigation.navigate('chat')
            }
        } catch (error) {
            console.log(error)
        }
        setLoading(false)
    }


    const isItem = (item) => {
        return list.find(el => el.F == item.F)
    }
    const setListItem = (item, index) => {
        if (isItem(item)) {
            const ar = list.filter((v, index) => { return v.F !== item.F })
            setList(ar)
        } else {
            setList([...list, item])
        }
    }
    return (
        <SafeAreaView style={styles.container}>
            <FlatList
                style={[styles.row, { flex: 1 }]}
                renderItem={({ item, index }) => {
                    return (
                        <TouchableWithoutFeedback key={index} onPress={() => setListItem(item, index)}>
                            <View style={styles.li}>
                                <View style={[styles.flexDirectionRow]}>
                                    <View style={[styles.icon, isItem(item) && styles.iconCurrent]}>
                                        {isItem(item) && <IconFont name="success" color={"#fff"} size={pTx(14)} />}
                                    </View>
                                    <View style={[styles.flexDirectionRow]}>
                                        <Avatar style={styles.avatar} source={{ uri: item.P }} />
                                        <View style={styles.cell}>
                                            <Text style={styles.name}>{item.R}</Text>
                                        </View>
                                    </View>
                                </View>
                            </View>
                        </TouchableWithoutFeedback>
                    )
                }}
                data={friendList}
                keyExtractor={(item, index) => index}
            />
        </SafeAreaView>
    )
}

const mapStateToProps = (state) => state.app

const mapDispatchToProps = {
}

export default connect(mapStateToProps, mapDispatchToProps)(CreateGroupChat)

const styles = StyleSheet.create({
    headerTitleObx: {
        marginRight: pTx(15),
        paddingVertical: pTx(5),
        paddingHorizontal: pTx(7),
        backgroundColor: "rgba(0,0,0,0.2)",
        borderRadius: pTx(8),
    },
    headerTitle: {
        color: "rgba(255,255,255,0.7)",
        fontSize: pTx(13),

    },
    headerTitleHave: {
        color: "#fff",
        backgroundColor: "rgba(6, 193, 97, 1)",
    },
    container: {
        flex: 1,
        backgroundColor: "#fff",
    },
    flexDirectionRow: {
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
    },
    li: {
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
        paddingVertical: pTx(10),
        paddingHorizontal: pTx(15),
        borderBottomColor: "rgba(175,181,189,0.15)",
        borderBottomWidth: 1
    },
    icon: {
        marginRight: pTx(10),
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "center",
        width: pTx(24),
        height: pTx(24),
        borderWidth: 1,
        borderColor: "rgba(0,0,0,0.1)",
        borderRadius: pTx(14),
    },
    iconCurrent: {
        backgroundColor: "rgba(6, 193, 97, 1)",
    },
    applyMsg: {
        minWidth: pTx(22),
        paddingHorizontal: pTx(7),
        paddingVertical: pTx(2),
        borderRadius: pTx(38),
        textAlign: "center",
        color: "#fff",
        fontWeight: "500",
        fontSize: pTx(12),
        backgroundColor: "#ee0a24"
    },
    avatar: {
        width: pTx(38),
        height: pTx(38),
        borderRadius: pTx(6),
    },
    cell: {
        marginLeft: pTx(12),
    },
    name: {
        fontSize: pTx(16),
        color: "#0A0C14"
    },
})